<?php
class UsersController extends AppController
{
    var $name = 'Users';
    var $scaffold;
    function index() {
        $this->needPermissions('FULL_CONTROL');
        $users = array();
        foreach($this->User->find('all') as $objUser)
        {
            $user = $objUser['User'];
            $user['roles'] = $objUser['Role'];
            $users[] = $user;
        }
        $this->set('users', $users);
    }
    
    function edit($id) {
        $this->needPermissions('FULL_CONTROL');
        $this->pageStyles[] = "user.source";
        $_data = $this->User->find('first', array('conditions' => array('User.id'=>$id)));
        if(count($_data) <= 0) {
            $errorCode = 1;
        } else {
            $this->set('user', $_data['User']);
        }
    }
    
    function login() {
    	$this->pageStyles[] = "user.source";
        if (!empty($this->data)) {
            $_data = $this->data['User'];
            $username = $this->input($_data['username']);
            $password = sha1($this->input($_data['password']));
            $_user = $this->User->find('first', array('conditions' => array('User.user_name'=>$username)));
            if(count($_user) <= 0) {
                $errorCode = 1;
            } else {
                if($password === $_user['User']['user_pass']){
                    $errorCode = 0;
                } else {
                    $errorCode = 2;
                }
            }
            if($errorCode == 0) {
                $userSession = $_user['User'];
                $_perms = array();
                foreach($_user['Role'] as $_role) {
                    $_perms = array_unique(am($_perms, explode(',', $_role['permissions'])));
                }
                $userSession['permissions'] = $_perms;
                $this->Session->write('user', $userSession);
                $this->redirect("/");
            }
        }
    }
    
    function beforeRender() {
        
        parent::beforeRender();
    }
}